package com.xiaomi.eco.config;

import com.mi.oa.infra.oaucf.core.dto.BaseResp;
import com.mi.oa.infra.oaucf.idm.api.IdmAccountV2Service;
import com.mi.oa.infra.oaucf.newauth.core.authority.api.dto.AccountAuthorityResp;
import com.mi.oa.infra.oaucf.newauth.core.authority.api.remote.AuthorityClientService;
import com.mi.oa.infra.oaucf.newauth.core.userdetail.Identity;
import com.mi.oa.infra.oaucf.newauth.core.userdetail.IdentityDetail;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;


@Component
public class OauchExecutor {
    @Value("${oaucf.idm-api.appId}")
    private String appId;

    @Resource
    private AuthorityClientService authorityClientService;


    public LoginInfo getAccount() {
        Identity identity = getIdentity();
        if (identity != null) {
            LoginInfo loginInfo = LoginInfo.builder()
                    .userCode(identity.getValue())
                    .userName(identity.getUserInfoDto().getUserName())
                    .build();
            return loginInfo;
        }
        return null;
    }

    private AccountAuthorityResp getAuthDetail() {
        Identity identity = getIdentity();
        BaseResp<AccountAuthorityResp> resp = authorityClientService.queryAccountAuth(identity.getValue(), getAccountType(identity.getLoginType()), appId);
        if (resp == null || resp.getData() == null) {
            throw new RuntimeException("could not retrieve auth detail");
        }
        return resp.getData();
    }

    private Identity getIdentity() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication.getPrincipal() instanceof IdentityDetail) {
            return ((IdentityDetail) authentication.getPrincipal()).getIdentity();
        }
        throw new RuntimeException("could not retrieve user identity");
    }

    private String getAccountType(Identity.LoginType loginType) {
        switch (loginType) {
            case CAS:
                return "INTRA";
            case PASSPORT:
                return "MILIAO";
            default:
                throw new RuntimeException("unknown loginType supplied");
        }
    }

}
